
var functionList;
$(document).ready(function () {
    var jstree = $('#using_json').jstree({
        'core': {
            'data': null,
            'multiple':false
        },
        "plugins" : ["contextmenu"],
        "contextmenu":{
            "items":{
                "New":{
                    "label":"新建子功能" ,
                    "action":function(data){
                        var inst = jQuery.jstree.reference(data.reference),
                            obj = inst.get_node(data.reference);
                        AddChildNode(obj);
                    }
                },
                "Edit":{
                    "label":"编辑本功能",
                    "action":function(data){
                        var inst = jQuery.jstree.reference(data.reference),
                            obj = inst.get_node(data.reference);
                        editNode(obj);
                    }
                },
                "Delete":{
                    "label":"删除本功能",
                    "separator_after":true ,
                    "action":function(data){
                        var inst = jQuery.jstree.reference(data.reference),
                            obj = inst.get_node(data.reference);
                        deleteNode(obj);
                    }
                },
                "Refresh":{
                    "label":"刷新",
                    "action":function(data){
                        loadFunctionData();
                    }
                }
            }
        }
    });
    jstree.on('changed.jstree', function (e, data) {
        var i, j, r = [];
        for(i = 0, j = data.selected.length; i < j; i++) {
            editNode(data.instance.get_node(data.selected[i]));
        }
    });
    // listen for event
    loadFunctionData();
});
function loadFunctionData(){
    $(".loading").css("top",$(window).height() / 2 - 30);
    //displayLoading(true);
    $.post("/manage/system/getAllForTree",{"functionId":0},
        function(data){
            if(data.status==1){//登陆成功
                //加载用户信息
                functionList = data.result;
                loadTreeData();
            }
            else if(data.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(data.status==5){
                alert(data.msg);
                window.location.href="/manage/login.html";
            }
            else{
                alert(data.msg);
            }
            hiddenLoading(true);
        });
}
function loadTreeData(){
    var treeNodes = "[";
    for(var i = 0;i<functionList.length;i++){
        if(i==0){
            treeNodes+='{"id":"';
        }
        else{
            treeNodes+=',{"id":"';
        }
        treeNodes+= functionList[i].functionId+'","parent":"';
        treeNodes+= functionList[i].functionParentid+'","text":"',
            treeNodes+=  functionList[i].functionName+'","functionUrl":"';
        treeNodes+= functionList[i].functionUrl+'","functionUrl":';
        treeNodes+= functionList[i].functionOrder+',"functionOrder":"'
        treeNodes+= functionList[i].language+'"}';
    }
    treeNodes+="]";
    treeNodes = treeNodes.replace(new RegExp('"null"',"gm"),"null");
    treeNodes = treeNodes.replace(new RegExp('"0"',"gm"),'"#"');
    var jsonNodes = JSON.parse(treeNodes);
    $('#using_json').jstree(true).settings.core.data=jsonNodes;
    $('#using_json').jstree(true).refresh();
}
function AddChildNode(node){
    for(i=0;i<functionList.length;i++){
        if(node.id==functionList[i].functionId){
            $("#functionId").val(0);
            $("#functionName").val("");
            $("#functionParentid").val(functionList[i].functionId);
            $("#functionParentname").val(functionList[i].functionName);
            $("#functionIco").val("");
            $("#functionMenuId").val(-1);
            $('input:radio[name="language"][value="'+functionList[i].language+'"]').next().click();
            $('input:radio[name="functionIsInterface"][value="0"]').next().click();
            $("#edit-title").html("正在新增【"+functionList[i].functionName+"】的子节点");
        }
    }
}
function editNode(node){
    for(i=0;i<functionList.length;i++){
        if(node.id==functionList[i].functionId){
            $("#functionId").val(functionList[i].functionId);
            $("#functionName").val(functionList[i].functionName);
            $("#functionOrder").val(functionList[i].functionOrder);
            $("#functionUrl").val(functionList[i].functionUrl);
            $("#functionIco").val(functionList[i].functionIco);
            $("#functionMenuId").val(functionList[i].functionMenuId);
            //更新父节点
            $("#functionParentid").val(functionList[i].functionParentid);
            if(functionList[i].functionParentid!=0){
                for(j=0;j<functionList.length;j++){
                    if(functionList[i].functionParentid==functionList[j].functionId){
                        $("#functionParentname").val(functionList[j].functionName);
                    }
                }
            }
            else{
                $("#functionParentname").val('顶级节点');
            }
            $('input:radio[name="language"][value="'+functionList[i].language+'"]').next().click();
            $('input:radio[name="functionIsInterface"][value="'+(functionList[i].functionIsInterface?1:0)+'"]').next().click();

            $("#edit-title").html("正在编辑【"+functionList[i].functionName+"】");
        }
    }
}
function deleteNode(node){
    parent.layer.confirm('确认要删除"'+node.text+'"吗？', {icon: 3, title:'提示'}, function(index){
        deleteNodeToServer(node.id);
        parent.layer.close(index);

    });
}
layui.use(['form'], function(){
    var form = layui.form;

    //自定义验证规则
    form.verify({
        title: function(value){
            if(value.length < 2){
                return '标题至少得2个字符啊';
            }
        }
    });

    //监听提交
    form.on('submit(demo1)', function(data){
        //JSON.stringify(data.field)
        updateNodeToServer();
        return false;
    });
});
function deleteNodeToServer(parentId){
    displayLoading(true);
    $.post("/manage/system/deleteFunction",{"functionId":parentId},
        function(data){
            if(data.status==1){//登陆成功
                loadFunctionData();
            }
            else if(data.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(data.status==5){
                parent.layer.msg(data.msg, {icon: 1});
                window.location.href="/manage/login.html";
            }
            else{
                parent.layer.msg(data.msg, {icon: 1});
            }
            hiddenLoading(true);
        });
}
function updateNodeToServer(){
    displayLoading(true);
    $.post("/manage/system/updateFunction",$('.layui-form').serialize(),
        function(data){
            if(data.status==1){//登陆成功
                loadFunctionData();
            }
            else if(data.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(data.status==5){
                parent.layer.msg(data.msg, {icon: 1});
                window.location.href="/manage/login.html";
            }
            else{
                parent.layer.msg(data.msg, {icon: 1});
            }
            hiddenLoading(true);
        });
}
//自动关联同名菜单ID
$("#functionName").blur(function(){
    if($.trim($(this).val())==""){
        return;
    }
    else{
        $.post('/manage/system/getMenuByName',{menuName:$.trim($(this).val())},function(data){
            if(data.status==1){//登陆成功
                if(data.result){
                    $('#functionMenuId').val(data.result.menuId);
                }
                else{
                    //$('#functionMenuId').val("-1");
                }
            }
            else if(data.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(data.status==5){
                parent.layer.msg(data.msg, {icon: 1});
                window.location.href="/manage/login.html";
            }
            else{
                parent.layer.msg(data.msg, {icon: 1});
            }
        });
    }
});